package com.logic.landseaserver.models.useranswer.service;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.logic.common.security.SecurityUtils;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.exception.ResultCodes.UserAnswersResultCode;
import com.logic.landseaserver.domain.UserAnswers;
import com.logic.landseaserver.models.useranswer.bean.UserAnswerReq;
import com.logic.landseaserver.models.useranswer.bean.UserAnswerResp;
import com.logic.landseaserver.persistence.read.UserAnswersReadMapper;
import com.logic.landseaserver.persistence.write.UserAnswersWriteMapper;

@Service
public class UserAnswerService
{
    private static final Logger LOGGER = LoggerFactory.getLogger(UserAnswerService.class);
    
    @Autowired
    private  UserAnswersWriteMapper userAnswersWriteMapper;
    
    @Autowired
    private  UserAnswersReadMapper userAnswersReadMapper;
      
    public List<UserAnswerResp> getUserAnswerList()throws LandseaException
    {
        List<UserAnswerResp> userAnswerRespList = userAnswersReadMapper.queryUserAnswerList();
        return userAnswerRespList;
    }

    public void saveUserAnswer(List<UserAnswerReq> userAnswerReqList)throws LandseaException
    {
        try
        {
        if (CollectionUtils.isEmpty(userAnswerReqList))
        {
            throw LandseaException.createException(UserAnswersResultCode.E00750001);
        }
        else 
        {
            userAnswersWriteMapper.deleteAllPhysical();
            for (UserAnswerReq userAnswerReq : userAnswerReqList)
            {
                UserAnswers saveUserAnswer = new UserAnswers();
                saveUserAnswer.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
                saveUserAnswer.setAnswer(userAnswerReq.getAnswer());
                saveUserAnswer.setQuestion(userAnswerReq.getQuestion());
                saveUserAnswer.setId(userAnswerReq.getId());
                userAnswersWriteMapper.insert(saveUserAnswer);
            }
        }
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOGGER.error("saveUserAnswer|保存问题失败.", e);
            throw LandseaException.createException(UserAnswersResultCode.E00750002);
        }
        
    }
}
    
